package com.dcd.util;

import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/*Aes加密*/
@Component
public class AesUtil {
    private static final String SECRET_KEY = "DONCHEDIDONCHEDI";
    private static final String KEY_AES = "AES";

    /*加密*/
    public String encrypt(String context) throws Exception {
        byte[] raw = SECRET_KEY.getBytes();
        SecretKeySpec skySpec = new SecretKeySpec(raw, KEY_AES);
        Cipher cipher = Cipher.getInstance(KEY_AES);
        cipher.init(Cipher.ENCRYPT_MODE, skySpec);
        byte[] encrypted = cipher.doFinal(context.getBytes());
        return byte2hex(encrypted);
    }

    /*解密*/
    public String decrypt(String context) throws Exception {
        byte[] raw = SECRET_KEY.getBytes();
        SecretKeySpec skySpec = new SecretKeySpec(raw, KEY_AES);
        Cipher cipher = Cipher.getInstance(KEY_AES);
        cipher.init(Cipher.DECRYPT_MODE, skySpec);
        byte[] encrypted1 = hex2byte(context);
        byte[] original = cipher.doFinal(encrypted1);
        return new String(original);
    }

    public static byte[] hex2byte(String hex) {
        if (hex == null) {
            return new byte[0];
        }
        int l = hex.length();
        int n = 2;
        if (l % n == 1) {
            return new byte[0];
        }
        byte[] b = new byte[l / 2];
        for (int i = 0; i != l / n; i++) {
            b[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2),
                    16);
        }
        return b;
    }

    public static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String tmp;
        for (byte value : b) {
            tmp = (Integer.toHexString(value & 0XFF));
            if (tmp.length() == 1) {
                hs.append("0").append(tmp);
            } else {
                hs.append(tmp);
            }
        }
        return hs.toString().toUpperCase();
    }
}
